package com.emergency.examine.service.impl;

import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.examine.dao.*;
import com.emergency.examine.domain.*;
import com.emergency.examine.service.ExamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExamServiceImpl implements ExamService {
    private final static Logger logger = LoggerFactory.getLogger(ExamServiceImpl.class);

    @Autowired
    private ExamDao examDao;

    @Autowired
    private ExamAnswerDao examAnswerDao;

    @Autowired
    private QuestionScoreDao questionScoreDao;

    @Autowired
    private IdWorker idWorker;

    //添加考试信息
    @Override
    public String save(Exam exam) {
        if (CommonUtils.isNullOrEmpty(exam.getId())) {
            exam.setId(idWorker.nextId());
            exam.setCreateTime(new Date());
        }
        //保存考试信息
        examDao.save(exam);
        examAnswerSave(exam);
        questionScoreSave(exam);
        return exam.getId().toString();
    }

    //保存考生答题信息
    private void examAnswerSave(Exam exam) {
        List<ExamAnswer> examAnswers = exam.getExamAnswer();
        if (!CommonUtils.isNullOrEmpty(examAnswers)) {
            examAnswers.forEach(examAnswer -> {
                examAnswer.setId(idWorker.nextId());
                examAnswer.setCreateTime(new Date());
                examAnswer.setExam(exam);
            });
        }
        examAnswerDao.saveAll(examAnswers);
    }

    //保存考生答题得分
    private void questionScoreSave(Exam exam) {
        List<QuestionScore> questionScores = exam.getQuestionScore();
        if (!CommonUtils.isNullOrEmpty(questionScores)) {
            questionScores.forEach(questionScore -> {
                questionScore.setId(idWorker.nextId());
                questionScore.setCreateTime(new Date());
                questionScore.setExam(exam);
            });
        }
        questionScoreDao.saveAll(questionScores);
    }

    //获取考试信息
    @Override
    public Exam getInfo(Long examId) {
        Exam exam = examDao.findById(examId).orElse(null);
        if (CommonUtils.isNullOrEmpty(exam)) {
            logger.info("没有这场考试信息");
            return exam;
        }
        //获取考生答题
        exam.setExamAnswer(examAnswerDao.findAllByExam(examId));

        //获取考生题目得分
        exam.setQuestionScore(questionScoreDao.findAllByExam(examId));

        return exam;
    }

    //删除考试信息
    @Override
    public void del(Long examId) {
        examAnswerDao.deleteByExamId(examId);
        questionScoreDao.deleteByExamId(examId);
        examDao.deleteById(examId);
    }

    //查询
    @Override
    public Page<Exam> findList(Map searchMap, int page, int size) {
        Specification<Exam> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return examDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Exam> createSpecification(Map searchMap) {

        return new Specification<Exam>() {

            @Override
            public Predicate toPredicate(Root<Exam> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 考试名称
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                // 考试类型
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(cb.like(root.get("type").as(String.class), "%" + (String) searchMap.get("type") + "%"));
                }
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
